package com.wind.util;

import cn.hutool.core.util.StrUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Value;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName SmsUtil
 * @Description Hey, it's compiled! Pack it!
 * @Author Administrator
 * @Date 2021/5/25 19:57
 * @Version 1.0
 */
public class SMSUtil {

    public final static String keys = "";

    private final static String product = "";

    private final static String domain = "dysmsapi.aliyuncs.com";

    private static String accessKeyId = "";

    private static String accessKeySecret = "";

    private static String signName = "";

    private static String identifyingTempleteCode = "";// 短信验证模板

    public void init(String accessKeyId, String accessKeySecret,
                     String signName, String identifyingTempleteCode) {
        SMSUtil.accessKeyId = accessKeyId;
        SMSUtil.accessKeySecret = accessKeySecret;
        SMSUtil.signName = signName;
        SMSUtil.identifyingTempleteCode = identifyingTempleteCode;
    }

    public static SendSmsResponse SendSmsResponse(String phone,
                                                  String templateParam, String templateCode) throws ClientException {

        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        // 初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product,
                domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        // 组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();

        // 必填:待发送手机号
        request.setPhoneNumbers(phone);
        // 必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        // 必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);

        // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(templateParam);

        // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("yourOutId");

        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }

    //短信验证码
    public static Map<String, Object> SendSms(String phone) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (!StrUtil.isBlank(phone)) {
                boolean result = isChinaPhoneLegal(phone);
                if (result) {
                    String code = SMS.getSms();
                    code=getCode(phone);
                    String TemplateParam = "{\"code\":\"" + code + "\"}";
                    SendSmsResponse sendSmsResponse = SendSmsResponse(phone,
                            TemplateParam, identifyingTempleteCode);
                    if (sendSmsResponse != null) {
                        System.out.println("Msg:" + sendSmsResponse.getMessage()
                                + " | phone:" + phone + " | SMSCode:" + code);
                        if (sendSmsResponse.getCode().equals("OK")) {

                            RedisUtil.set(KeyPrefixConst.key_sms+phone, code, 5*60);

                            resultMap.put("code", 200);
                            resultMap.put("msg", "发送成功");
                            return resultMap;
                        }
                        resultMap.put("code", 201);
                        resultMap.put("msg", sendSmsResponse.getMessage());
                        return resultMap;
                    }
                }
                resultMap.put("code", 401);
                resultMap.put("msg", "手机号码不正确");
                return resultMap;
            }
            resultMap.put("code", 404);
            resultMap.put("msg", "手机号码不能为空");
        } catch (ClientException e) {
            System.out.println(e);
        }
        return resultMap;
    }

    /**
     * 验证手机号
     *
     * @param phone
     * @return
     */
    public static boolean isChinaPhoneLegal(String phone) {
        String regExp = "^(13[0-9]|14[456789]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[189])\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(phone);
        return m.matches();
    }

    /**
     * 随机生成6位数字
     *
     * @return
     */
    public static String getCode(String phoneNumber) {
        String chars = "1234567890";
        String code = "";
        for (int i = 0; i < 6; i++) {
            Random r = new Random();
            code += chars.charAt(r.nextInt(chars.length() - 1));
        }
        return code;
    }


}
